<?PHP

/**
 * 仓库管理类接口控制器
 * Class DepotAction
 * @author lilei<LL_strive@163.com> 2017-04-01
 */
class DepotAction extends Action {

    /**
     * 根据查询条件模糊查询出所有仓库信息
     *
     * @param null   $name      按name筛选
     * @param null   $isExport  是不是导出操作
     * @param string $order     排序字段
     * @param string $orderBy   排序规则
     * @param int    $start     起始偏移量
     * @param int    $limit     查询数量
     * @param int    $vid     商家id
     * @param int    $did    仓库id
     * @param string    $show   只显示自己商家下的数据,self
     *
     * @author lilei<LL_strive@163.com> 2017-04-01
     */
    public function getDepotList($name = null, $isExport = null, $order = 'updateTime', $orderBy = 'desc', $start = 0, $limit = 25,$vid='',$did='',$show='')
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user["id"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $DepotModel = M("depot");
        $customerUser = M("customer_user");

        /** 3. 组织查询条件 */
        $where['depot.deleted'] = array('eq', 0);
        $where['depot.cid']     = array('eq', $customerId);
        if ($did){
            $where['depot.id'] = $did;
        }else{
            if ($vid) {
                $userVid = $vid;
                $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                $where['depot.vid'] = array('IN', $vids);
            }else {
                if (Session::isVendor()){
                    //mh修改于20180622
                    //$userVid = $customerUser->where("id=$cuid")->getField('vid');
                    $userVid = $customerUser->where("id=$cuid")->getField('vid');
                    if ($show) {
                        $where['depot.vid'] = array('eq', $userVid);
                    } else {
                        //mh修改于20180620，用户渠道体系升级，改用in查询
                        $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                        $where['depot.vid'] = array('IN', $vids);
                    }
                }
            }
        }
        $name ? $where['depot.name'] = array('like', "%{$name}%") : '';

        /** 4. 查询仓库表获得仓库信息 */
        $result = $DepotModel
            ->alias("depot")
            //->join('wx_customer_user as cu ON depot.cuid = cu.id')  // 关联用户表, 查询出该仓库的管理员信息
            ->join('wx_mivendor as mi ON depot.vid = mi.id')  // 关联仓库表, 查询出该仓库的信息
            ->where($where)
            ->order("$order $orderBy")->limit("$start, $limit")
            //->field("depot.*, cu.id as cuid, cu.loginName, cu.fullName, cu.phone")
            ->field("depot.*,mi.name as vendorName")
            ->select();
        /** 5. 判断查询结果并返回 */
        if ($result) {
            $count = $DepotModel
            ->alias("depot")
            ->join('wx_mivendor as mi ON depot.vid = mi.id')  // 关联仓库表, 查询出该仓库的信息
            ->where($where)
            ->field("depot.*,mi.name as vendorName")
            ->count();
            if (!$isExport) {
                Output::instance()->objArray($result,$count);
            } elseif ($isExport == 1) {
                $data[0] = array(
                    'temp'      => "",
                    'name'      => '仓库名称',
                    // 'fullName'  => '管理员姓名',
                    // 'phone'     => '管理员TEL',
                    'address'   => '仓库地址',
                    'coordinate'=> '坐标',
                    'desc'      => '仓库描述',
                    'isNum'     => '',
                    'istitle'   => '1'
                );
                foreach ($result as $k1 => $v1) {
                    $data[$k1+1]['temp']        = '';
                    $data[$k1+1]['name']        = $v1['name'];
                    // $data[$k1+1]['fullName']    = $v1['fullName'];
                    // $data[$k1+1]['phone']       = $v1['phone'];
                    $data[$k1+1]['address']     = $v1['province'] . $v1['city'] . $v1['conutry'] . $v1['address'];
                    $data[$k1+1]['coordinate']  = '经:' . $v1['longitude'] . ' 纬:' . $v1['latitude'];
                    $data[$k1+1]['desc']        = $v1['desc'];
                }
                Output::instance()->objArrayExcel('仓库信息'.date("Y-m-d H:i:s"), '', $data);
            }
        } else {
            Output::instance()->resultCode(code_success);
        }
    }

    /**
     * 增加一个仓库
     *
     * @param $name         /仓库名
     * @param $province     /仓库所在省
     * @param $city         /仓库所在市
     * @param $area         /仓库所在区
     * @param $address      /仓库所在详细地址
     // * @param $fullName         管理员姓名
     // * @param $phone         管理员手机号
     // * @param $loginName         管理员登录名
     // * @param $password         管理员密码
     // * @param $longitude    仓库经度
     // * @param $latitude     仓库纬度
     * @param $desc         /仓库描述
     * @return mixed|void   增加仓库的操作结果
     *
     * @author lilei<LL_strive@163.com> 2017-04-01
     */
    public function addDepot(
        $name,
        $province,
        $city,
        $area,
        $address,
        $desc='',
        $vid=''
        // $fullName='',
        // $phone='',
        // $loginName='',
        // $password='',
        // $longitude='',
        // $latitude=''
    ) {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $DepotModel = M('depot');
        $CustomerUserModel = M('customer_user');

        // 判断该用户是否已存在【新升级的仓库系统中不需要这里的逻辑】孟慧修改于20180226
        // $result = $this->isExistUser($loginName);
        // if ($result) {
        //     Output::instance()->resultCode(code_user_exist);
        //     return;
        // }
        
        /** 3. 组织增加的仓库数据 */
        $cuid = Session::$user['id'];
        //mh修改于20180620，修改获取id方式
        //$vid = $CustomerUserModel->where("id=$cuid")->getField('vid');
        $dataDepot = [
            'cid'           => $customerId,
            'name'          => $name,
            'province'      => $province,
            'city'          => $city,
            'country'       => $area,
            'address'       => $address,
            // 'longitude'     => $longitude,
            // 'latitude'      => $latitude,
            'desc'          => $desc,
            'vid'           => $vid,
            'createTime'    => date("Y-m-d H:i:s"),
            'updateTime'    => date("Y-m-d H:i:s"),
            'deleted'       => 0
        ];

        // 添加用户信息【新升级的仓库系统中不需要这里的逻辑】孟慧修改于20180226
        // $dataCustomerUser = [
        //     'customerId' => $customerId,
        //     'agent'      => 'depot',
        //     'loginName'  => $loginName,
        //     'password'   => Encryption::password($password),
        //     'registered' => date("Y-m-d H:i:s"),
        //     'fullName'   => $fullName,
        //     'phone'      => $phone,
        //     'status'     => 'open'
        // ];

        /** 4. 执行sql增加操作 */
        //添加用户cuid信息【新升级的仓库系统中不需要这里的逻辑】孟慧修改于20180226
        // $resultCustomerUserId = $CustomerUserModel->add($dataCustomerUser);
        // $dataDepot['cuid'] = $resultCustomerUserId;
        $resultDepotId = $DepotModel->add($dataDepot);

        /** 5. 返回结果*/
        if (!$resultDepotId) {
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        R('Log/add', array('newDepotManagement', module_id_newDepotManagement, '仓库管理', op_add, $DepotModel->getLastSql(), '添加仓库：' . $name));
        $return['code'] = 0;
        $return['msg'] = 'ok';
        $return['id'] = $resultDepotId;
        Output::instance()->object($return);
    }

    /**
     * 根据仓库id查询某个指定仓库的信息
     *
     * @param $id   指定仓库的id
     * @return      返回该仓库信息对象
     *
     * @author lilei<LL_strive@163.com> 2017-04-01
     */
    public function getDepotById($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $DepotModel = M("depot");

        /** 3. 组织查询条件 */
        $condition['depot.id'] = array('eq', $id);
        $condition['depot.cid']     = array('eq', $customerId);

        /** 4. 查询仓库表获得该仓库信息 */
        $depot = $DepotModel
            ->alias("depot")
            //->join('wx_customer_user as cu ON depot.cuid = cu.id')
            ->join('wx_mivendor as mi ON depot.vid = mi.id')
            ->where($condition)
            //->field("depot.*, cu.id as cuid, cu.loginName, cu.password, cu.fullName, cu.phone")
            ->field("depot.*,mi.name as vendorName")
            ->find();
        /** 5. 判断查询结果并返回 */
        if ($depot) {
            Output::instance()->object($depot);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 更新某个仓库信息
     *
     * @param $id           /需要更新的仓库id
     * @param $name         /更新后的仓库名
     * @param $province     /更新后仓库所在省
     * @param $city         /更新后仓库所在市
     * @param $area         /更新后仓库所在区
     * @param $address      /更新后仓库详细地址
     * @param $longitude    /更新后仓库经度
     * @param $latitude     /更新后仓库纬度
     * @param $desc         /更新后仓库描述
     * @return bool|void    更新操作结果
     *
     * @author lilei<LL_strive@163.com> 2017-04-01
     */
    public function updateDepot(
        $id,
        $name,
        $province,
        $city,
        $area,
        $address,
        $desc='',
        $vid=''
        // $fullName,
        // $phone,
        // $loginName,
        // $password,
        // $longitude,
        // $latitude,
        // $cuid,
    ) {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $DepotModel = M("depot");
        $CustomerUserModel = M('customer_user');

        // 判断该用户是否已存在
        // $result = $this->isExistUser($loginName, $cuid);
        // if ($result) {
        //     Output::instance()->resultCode(code_user_exist);
        //     return;
        // }

        /** 3. 组织查询条件与更新数据 */
        $whereDepot['id']  = array('eq', $id);
        $whereDepot['cid'] = array('eq', $customerId);
        $dataDepot = [
            'cid'           => $customerId,
            'name'          => $name,
            'province'      => $province,
            'city'          => $city,
            'country'       => $area,
            'address'       => $address,
            'vid'       => $vid,
            // 'longitude'     => $longitude,
            // 'latitude'      => $latitude,
            'desc'          => $desc,
            'updateTime'    => date("Y-m-d H:i:s"),
        ];
        // $whereCustomerUser['id'] = array('eq', $cuid);
        // $dataCustomerUser = [
        //     'loginName'  => $loginName,
        //     'fullName'   => $fullName,
        //     'phone'      => $phone,
        //     'updateTime' => date("Y-m-d H:i:s")
        // ];
        // $DBpassword = $CustomerUserModel->where($whereCustomerUser)->getField('password');
        // if ($password != $DBpassword) { // 表单中密码串与数据库不一样, 表示修改了密码
        //     $dataCustomerUser['password'] = Encryption::password($password);
        // }
        /** 4. 执行更新操作 */
        $resultDepot = $DepotModel->where($whereDepot)->save($dataDepot);
        //$resultCustomerUser = $CustomerUserModel->where($whereCustomerUser)->save($dataCustomerUser);

        /** 5. 返回更新结果*/
        if (!$resultDepot) {
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        R('Log/add', array('newDepotManagement', module_id_newDepotManagement, '仓库管理', op_update, $DepotModel->getLastSql(), '修改仓库信息：' . $name));
        $return['code'] = 0;
        $return['msg'] = 'ok';
        $return['id'] = $resultDepot;
        Output::instance()->object($return);
    }

    /**
     * 软删除指定仓库
     *
     * @param $id           需要删除的仓库id
     //* @param $cuid         需要连同删除的仓库管理员
     * @return bool|void    删除操作结果
     *
     * @author lilei<LL_strive@163.com> 2017-04-01
     */
    public function deleteDepot($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $DepotModel = M("depot");
        $CustomerUserModel = M('customer_user');

        /** 3. 组织删除条件和删除数据 */
        $whereDepot['id']  = array('eq', $id);
        $whereDepot['cid'] = array('eq', $customerId);
        $dataDepot = [
            'deleted'    => 1,
            'updateTime' => date("Y-m-d H:i:s"),
        ];
        // $whereCustomerUser['id'] = array('eq', $cuid);
        // $dataCustomerUser = [
        //     'status'     => 'close',
        //     'updateTime' => date("Y-m-d H:i:s"),
        // ];

        /** 4. 执行删除操作*/
        $resultDepot = $DepotModel->where($whereDepot)->save($dataDepot);
        $name = $DepotModel->where($whereDepot)->getField('name');
        //$resultCustomerUser = $CustomerUserModel->where($whereCustomerUser)->save($dataCustomerUser);

        /** 5. 返回删除结果 */
        if (!$resultDepot) {
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        R('Log/add', array('newDepotManagement', module_id_newDepotManagement, '仓库管理', op_update, $DepotModel->getLastSql(), '删除仓库：' . $name));
        Output::instance()->resultCode();
    }

    /**
     * 根据用户登录名判断用户是否已存在
     *
     * @param $loginName    登录名
     * @return true | false true表示存在
     *
     * @author lilei<LL_strive@163.com> 2017-04-05
     */
    protected function isExistUser($loginName, $cuid = null)
    {
        Session::switchCustomer(0);
        $CustomerUserModel = M('customer_user');

        $where['loginName'] = array('eq', $loginName);
        $where['deleted']   = array('eq', 0);
        if ($cuid) {
            $where['id'] = array('neq', $cuid);
        }
        $result = $CustomerUserModel->where($where)->select();
        if (count($result) > 0) {
            return true;
        }
        return false;
    }


    /**
     * 获得所有的渠道商以及渠道商下的仓库
     * @param string    $show   只显示自己商家下的数据,self
     * @author menghui
     */
    public function getAllDepot($name='',$show='')
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $mivendor = M("mivendor");
        $depot = M("depot");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        /** 3. 商家数据查询 */

        $whereMi['cId'] = array('eq', $customerId);
        $whereMi['deleted'] = array('eq', 0);
        $whereMi['name'] = array('like', "%$name%");
        //mh增加于20180620，用户渠道体系升级，改用in查询
        if (Session::isVendor()){
            $userVid = $customerUser->where("id=$cuid")->getField('vid');
            if ($show) {
                $whereMi['id'] = array('eq', $userVid);
            }else {
                 $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                 $whereMi['id'] = array('IN', $vids);
            }
        }
        $total = $mivendor->field('id,name')->where($whereMi)->count();
        $resultMi = $mivendor->field('id,name')->where($whereMi)->select();
        /** 4. 仓库数据查询 */
        if (!empty($resultMi)){
            foreach( $resultMi as $key => $value){
                $whereDepot['vid'] = array('eq', $value['id']);
                $whereDepot['cid'] = array('eq', $customerId);
                $whereDepot['deleted'] = array('eq', 0);
                $resultDepot = $depot->field('id,name')->where($whereDepot)->select();
                $resultDepot  = empty($resultDepot) ? [] : $resultDepot;
                $resultMi[$key]['depot'] = $resultDepot;
            }            
        }else{
            $resultMi = [];
            $total=0;
        }
    

        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = 'ok';
        $return['data'] = $resultMi;
        $return['total'] = $total;
        Output::instance()->object($return);
    }

     /**
     * 系统管理员新建调拨单
     * @param $outsideNumber   string 外部单号
     * @param $vid   int 供应商id
     * @param $depotId   int 仓库id
     * @param $depotName   string 仓库名称
 //    * @param $type   string 类型【outAllocation：外部调拨，inAllocation：内部调拨，return：退货】
     * @param $product   string 选中商品信息
     * @author menghui
     */
    public function newAllocation($outsideNumber,$vid,$depotId,$depotName,$product)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorStorage = M("vendor_storage");
        $vendorStorageDetail = M("vendor_storage_detail");
        //$productUnit = M("module_product_unit");
        $user_role_model = M('customer_user_role');
        $role_model = M('role');
        $customer_user_model = M('customer_user');
        Session::switchCustomer($customerId);

        /** 3. 商家数据查询 */
        $vendorStorage->startTrans();
        //入库数据添加
        $product = json_decode($product,true);
        $time = date('Y-m-d H:i:s',time());
        $storageNumber = $customerId . date("ymdHis") . $cuid;
        $add_storage['cid'] = $customerId;
        $add_storage['sponsorId'] = $cuid;
        $add_storage['sponsorName'] = $loginName;
        $add_storage['outsideNumber'] = $outsideNumber;
        $add_storage['vid'] = $vid;
        $add_storage['depotId'] = $depotId;
        $add_storage['depotName'] = $depotName;
        $add_storage['sponsorTime'] = $time;
        $add_storage['status'] = 'delivered';
        $add_storage['type'] = 'outAllocation';
        $add_storage['deleted'] = 0;
        $add_storage['storageNumber'] = $storageNumber;
        $newStorageId = $vendorStorage->add($add_storage);
        //详细入库单信息添加
        $table = '<table border="1"><tr><td><b>商品名称</b></td><td><b>规格</b></td><td><b>发货数量</b></td><td><b>发货单价</b></td></tr>';
        foreach ($product as $key => $value) {

            $add_detail['cid'] = $customerId;
            $add_detail['pid'] = $value['pid'];
            $add_detail['productName'] = $value['productName'];
            $add_detail['productUrl'] = $value['productUrl'];
            $add_detail['firstSpecificName'] = $value['firstSpecificName'];
            $add_detail['secSpecificName'] = $value['secSpecificName'];
            $add_detail['miunitPrice'] = $value['miunitPrice'];
            $add_detail['unit'] = $value['unit'];
            $add_detail['unitNumber'] = $value['unitNumber'];
            //获取换算关系
            //$unitConversion = $this->unitConversion($value);                   
            //$add_detail['miunitNumber'] = $unitConversion * $value['unitNumber'];                   
            $add_detail['miunitNumber'] = $value['unitNumber'];
            $add_detail['storageId'] = $newStorageId;
            $result_detail = $vendorStorageDetail->add($add_detail); 
            if ($result_detail == false) {
                $vendorStorage->rollback();
                /** 5. 返回结果 */
                $return['code'] = 1;
                $return['msg'] = '信息存储错误请重试';
                Output::instance()->object($return);
                exit();
            }
            $Specific = $value['firstSpecificName'] . $value['secSpecificName'];
            $table .= '<tr><td>' . $value['productName'] . '</td><td>' . $Specific . '</td><td>' . $value['unitNumber'] . '</td><td>' . $value['miunitPrice'] . '</td></tr>';
        }
        $table .= '</table>';

        if ($newStorageId){
            R('Log/add', array('newDepotInStorage', module_id_newDepotInStorage, '入库', op_add, $vendorStorage->getLastSql(), '给'.$depotName.'仓库添加调拨单'));
            $vendorStorage->commit();
            /** 5. 返回结果 */
            $return['code'] = 0;
            $return['msg'] = 'ok';
            $return['id'] = $newStorageId;
            //发送站内消息
//            $roleId = $role_model->where(['cid' => $customerId, 'englishRole' => 'operationCenterAdmin'])->getField('id');
//            $receiveIds = $user_role_model->alias('r')
//                ->join('wx_customer_user u on u.id = r.userId')
//                ->where(['r.cid' => $customerId, 'r.roleId' => $roleId, 'u.vid' => ['exp', 'is null']])
//                ->getField('r.userId', true);//接收人id集合数组
//            $receiveIds = array_unique($receiveIds);
            $receiveIds = $customer_user_model->where(['customerId' => $customerId, 'vid' => $vid])->getField('id', true);
            $message = '<p>' . $loginName . '向您发起了补货，补货仓库为：' . $depotName . '，发货单号为：' . $storageNumber . '，发货详情为：</p><p>' . $table . '</p><p>请前往入库模块查看，<a href = "#/joymap/depot/channel">前往查看</a></p>';
            PlatMessageAction::pushMessage('发起补货提醒', $message, $receiveIds, '', 0, 'newAllocation', '入库', 2, 1, 0, 0, $message, $customerId);
            Output::instance()->object($return);
        }else{
            $vendorStorage->rollback();
            /** 5. 返回结果 */
            $return['code'] = 1;
            $return['msg'] = '信息存储错误请重试';
            Output::instance()->object($return);
        }
    }

      /**
     * 调拨单列表
     * @param $start   int 开始值
     * @param $limit   int 偏移量
     * @param $search   string 搜索项
     * @param $status   string 状态值
     * @param $depotId   int 仓库id
     * @param $devStartTime   string 发货开始时间
     * @param $devEndTime   string 发货结束时间
     * @param $inStartTime   string 入库开始时间
     * @param $inEndTime   string 入库结束时间
     * @param $type   string 入库类型【管理员列表是outAllocation】
     * @param string    $show   只显示自己商家下的数据,self
     * @author menghui
     */
    public function allocationList($start=0,$limit=10,$search='',$status='',$depotId='',$type='',$devStartTime='',$devEndTime='',$inStartTime='',$inEndTime='',$vid='',$show='')
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user["id"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorStorage = M("vendor_storage");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        //判断角色，如果是商家的话需要加上商家的id限制
        if ($depotId){
            $where['a.depotId'] = $depotId;
        }else{
            if ($vid) {
                $userVid = $vid;
                $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                $where['a.vid'] = array('IN', $vids);
            }else {
                if (Session::isVendor()){
                    //mh修改于20180622
                    //$userVid = $customerUser->where("id=$cuid")->getField('vid');
                    $userVid = $customerUser->where("id=$cuid")->getField('vid');

                    if ($show) {
                        $where['a.vid'] = array('eq', $userVid);
                    }else {
                        //mh修改于20180620，用户渠道体系升级，改用in查询
                        $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                        $where['a.vid'] = array('IN', $vids);
                    }
                }
            }
        }
        if (!empty($search)) {     // 关键字查询
            $arg['a.storageNumber'] = array('like', "%$search%");
            //如果是商家看确认订单的时候搜索项中的操作人筛选是最后的确认收货人
            if ($status == 'confirm' && Session::isVendor()){
                $arg['a.confirmName'] = array('like', "%$search%");
            }else{
                $arg['a.sponsorName'] = array('like', "%$search%");
            }           
            $arg['_logic'] = "OR";
            $where["_complex"] = $arg;
        }
        //状态筛选、仓库筛选、类型筛选
        $status? $where['a.status'] = $status : '';
        $type? $where['a.type'] = $type : '';
        //生成入库单时间筛选
        if ($devStartTime != '' && $devEndTime != '') {
            $where['a.sponsorTime'] = array(array('egt', $devStartTime), array('elt', date('Y-m-d', strtotime("$devEndTime +1 day"))));
        } else if ($devStartTime != '') {
            $where["a.sponsorTime"] = array('egt', $devStartTime);
        } else if ($devEndTime != '') {
            $where["a.sponsorTime"] = array('elt', date('Y-m-d', strtotime("$devEndTime +1 day")));
        }
        //实际入库时间筛选
        if ($inStartTime != '' && $inEndTime != '') {
            $where['a.confirmTime'] = array(array('egt', $inStartTime), array('elt', date('Y-m-d', strtotime("$inEndTime +1 day"))));
        } else if ($inStartTime != '') {
            $where["a.confirmTime"] = array('egt', $inStartTime);
        } else if ($inEndTime != '') {
            $where["a.confirmTime"] = array('elt', date('Y-m-d', strtotime("$inEndTime +1 day")));
        }

        $where['a.deleted'] = 0;
        $where['a.cid'] = $customerId;
        $total = $vendorStorage->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->where($where)
                ->count();
        $result = $vendorStorage->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->field("a.*,b.name")
                ->where($where)
                ->order("a.id desc")
                ->limit($start,$limit)
                ->select();
        $result = empty($result) ? [] : $result;       
        $total = empty($total) ? 0 : $total;       
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        $return['total'] = $total;
        Output::instance()->object($return);
    }
      /**
     * 系统管理员调拨单基本信息查询
     * @param $id   int 入库单id
     * @author menghui
     */
    public function allocationBasicInfo($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorStorage = M("vendor_storage");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $where['a.id'] = $id;
        $result = $vendorStorage->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->field("a.*,b.name")
                ->where($where)
                ->find();  
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        Output::instance()->object($return);
    }

    /**
     * 系统管理员调拨单商品信息查询
     * @param $id   int 入库单id
     * @param $start   int 开始量
     * @param $limit   int 偏移量
     * @author menghui
     */
    public function allocationProductInfo($id,$start=0,$limit=10)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $detail = M("vendor_storage_detail");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $total = $detail->where("storageId=$id")->count();
        $total = empty($total) ? 0 : $total; 
        $result = $detail->where("storageId=$id")->limit($start,$limit)->select();
        $result = empty($result) ? [] : $result; 
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        $return['total'] = $total;
        Output::instance()->object($return);
    }

    /**
     * 系统管理员撤回调拨单
     * @param $id   int 入库单id
     * @author menghui
     */
    public function withdrawAllocation($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorStorage = M("vendor_storage");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $storage_info = $vendorStorage->field('status,depotName')->where("id=$id")->find();
        if ($storage_info['status'] == 'delivered') {
            $time = date('Y-m-d H:i:s',time());
            $save_data['status'] = 'withdraw';
            $save_data['withdrawTime'] = $time;
            $save_data['withdrawId'] = $cuid;
            $save_data['withdrawName'] = $loginName;
            $result = $vendorStorage->where("id=$id")->save($save_data);
            /** 5. 返回结果 */
            if ($result !== false) {
                R('Log/add', array('newDepotInStorage', module_id_newDepotInStorage, '入库', op_update, $vendorStorage->getLastSql(), '撤回给'.$storage_info['depotName'].'仓库的调拨单'));
                $return['code'] = 0;
                $return['msg'] = 'ok';
                Output::instance()->object($return);
            }else{
                $return['code'] = 1;
                $return['msg'] = '撤回失败，请重试';
                Output::instance()->object($return);
            }
        }else{
            $return['code'] = 1;
            $return['msg'] = '此状态的调拨单不能撤回';
            Output::instance()->object($return);
        }     
    }


    /**
     * 仓库管理人确认调拨单
     * @param $id   int 入库单id
     * @param $product   array 商品信息
     * @author menghui
     */
    public function confirmAllocation($id,$product)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorStorage = M("vendor_storage");
        $vendorStorageDetail = M("vendor_storage_detail");
        $stock = M("vendor_stock");
        //$productUnit = M("module_product_unit");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $vendorStorage->startTrans();
        $storage_info = $vendorStorage->field('status,vid,depotId,depotName,sponsorId,storageNumber')->where("id=$id")->find();
        if ($storage_info['status'] == 'delivered') {
            //修改调拨状态
            $time = date('Y-m-d H:i:s',time());
            $save_confirm['status'] = 'confirm';
            $save_confirm['confirmTime'] = $time;
            $save_confirm['confirmId'] = $cuid;
            $save_confirm['confirmName'] = $loginName;
            $result_status = $vendorStorage->where("id=$id")->save($save_confirm);

            $product = json_decode($product,true);
            //添加库存信息
            foreach ($product as $key => $value) {
                //查询仓库中是否已存在此商品
                $where_stock = [];
                $where_stock['cid'] = $customerId;
                $where_stock['pid'] = $value['pid'];
                empty($value['firstSpecificName']) ? : $where_stock['firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_stock['secSpecificName'] = $value['secSpecificName'];
                $where_stock['vid'] = $storage_info['vid'];
                $where_stock['depotId'] = $storage_info['depotId'];
                $find_stock = $stock->field('id,totalNumber,totalValue,realNumber')->where($where_stock)->find();
                //获取换算关系
                //$unitConversion = $this->unitConversion($value); 
                $realNumber = $value['realNumber'];

                //在出库详细里面添加实际数量以及剩余数量
                $where_storage_detail = [];
                $where_storage_detail['cid'] = $customerId;
                $where_storage_detail['pid'] = $value['pid'];
                empty($value['firstSpecificName']) ? : $where_storage_detail['firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_storage_detail['secSpecificName'] = $value['secSpecificName'];
                $where_storage_detail['storageId'] = $id;
                $save_storage_detail['realNumber'] = $realNumber;
                $save_storage_detail['surplusNumber'] = $realNumber;
                $result_detail = $vendorStorageDetail->where($where_storage_detail)->save($save_storage_detail);

                //已存在的话需要再此基础上增加各数值
                if ($find_stock){

                    $save_stock['totalNumber'] = $find_stock['totalNumber'] + $realNumber;
                    $save_stock['totalValue'] = $find_stock['totalValue'] + $realNumber * $value['miunitPrice'];
                    $save_stock['realNumber'] = $find_stock['realNumber'] + $realNumber;
                    $save_stock['updateTime'] = $time;
                    $result_stock = $stock->where("id=".$find_stock['id'])->save($save_stock);
                }else {

                    //获得商品的最小单位信息
                    // $where_unit['cid'] = $customerId;
                    // $where_unit['pid'] = $value['pid'];
                    // $where_unit['isBasicUnit'] = 1;
                    // $minUnit = $productUnit->where($where_unit)->getField('unitName');

                    //不存在的话直接填写各数值
                    $add_stock['cid'] = $customerId;
                    $add_stock['pid'] = $value['pid'];
                    $add_stock['productName'] = $value['productName'];
                    $add_stock['productUrl'] = $value['productUrl'];
                    $add_stock['firstSpecificName'] = $value['firstSpecificName'];
                    $add_stock['secSpecificName'] = $value['secSpecificName'];
                    //$add_stock['minUnit'] = $minUnit;
                    $add_stock['totalNumber'] = $realNumber;
                    $add_stock['totalValue'] = $realNumber * $value['miunitPrice'];
                    $add_stock['realNumber'] = $realNumber;
                    $add_stock['vid'] = $storage_info['vid'];
                    $add_stock['depotId'] = $storage_info['depotId'];
                    $add_stock['depotName'] = $storage_info['depotName'];
                    $add_stock['createTime'] = $time;
                    $add_stock['updateTime'] = $time;
                    $result_stock = $stock->add($add_stock);
                }
            log::write("针对调拨单id为".$id.'的调拨单添加库存'.$stock->getLastSql());
            /** 5. 返回结果 */
            if ($result_stock == false){
                $vendorStorage->rollback();
                $return['code'] = 1;
                $return['msg'] = '入库失败请重试';
                Output::instance()->object($return);
            }
          }
             /** 5. 返回结果 */
            if (($result_status !== false) && ($result_stock !== false)){
                R('Log/add', array('newDepotInStorage', module_id_newDepotInStorage, '入库', op_update, $vendorStorage->getLastSql(), '确认'.$storage_info['depotName'].'调拨单'));
                $vendorStorage->commit();
                /** 5. 返回结果 */
                $return['code'] = 0;
                $return['msg'] = 'ok';
                Output::instance()->object($return);
                //发送站内消息
                $receiveIds[] = $storage_info['sponsorId'];
                $message = '<p>您发起的发货单号为' . $storage_info['storageNumber'] . '的调拨记录已被确认，请前往调拨出库模块查看，<a href = "#/joymap/depot/allocation">前往查看</a></p>';
                PlatMessageAction::pushMessage('调拨确认提醒', $message, $receiveIds, '', 0, 'newAllocation', '调拨出库', 2, 1, 0, 0, $message, $customerId);
            }else{
                $vendorStorage->rollback();
                $return['code'] = 1;
                $return['msg'] = '入库失败请重试';
                Output::instance()->object($return);
            }
             
        }else{
            $vendorStorage->rollback();
            $return['code'] = 1;
            $return['msg'] = '此状态的调拨单不能确认';
            Output::instance()->object($return);
        }     
    }


   /**
     * 仓库商品列表
     * @param $start   int 开始值
     * @param $limit   int 偏移量
     * @param $search   string 搜索项
     * @param $depotId   int 仓库id
     * @author menghui
     */
    public function stockList($start=0,$limit=10,$search='',$depotId='',$vid='')
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"]; 
        $cuid = Session::$user["id"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $stock = M("vendor_stock");
        $customerUser = M("customer_user");
        //$productUnit = M("module_product_unit");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        //判断角色，如果是商家的话需要加上商家的id限制
        if ($depotId){
            $where['a.depotId'] = $depotId;
        }else{
            if ($vid) {
                $userVid = $vid;
                $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                $where['a.vid'] = array('IN', $vids);
            }else {
                if (Session::isVendor()){
                    //mh修改于20180622
                    //$userVid = $customerUser->where("id=$cuid")->getField('vid');
                    //$where['a.vid'] = array('eq', $userVid);
                    $userVid = $customerUser->where("id=$cuid")->getField('vid');
                    //mh修改于20180620，用户渠道体系升级，改用in查询
                    $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                    $where['a.vid'] = array('IN', $vids);
                }
            }
        }

        empty($search) ? '' : $where['a.productName'] = array('like', "%$search%");
        empty($depotId) ? '' : $where['a.depotId'] = $depotId;
        $where['a.cid'] = $customerId;
        $total = $stock->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->where($where)
                ->count();  
        $result = $stock->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                //->join("left join wx_module_product_unit c on a.pid=c.pid and isBasicUnit = 1")
                ->field("a.*,b.name")
                ->where($where)
                ->order("a.id desc")
                ->limit($start,$limit)
                ->select();
        // if ($result) {
        //     foreach($result as $key=>$value){
        //         $where_unit['pid'] = $value['id'];
        //         $where_unit['cid'] = $customerId;
        //         $unitInfo = $productUnit->where($where_unit)->select();
        //         $unitInfo = empty($unitInfo) ? [] : $unitInfo;
        //         $arr[$key]['unitInfo'] = $unitInfo;
        //         $arr[$key]['unitName'] = '';
        //         foreach ($unitInfo as $key1=>$value1) {
        //             if ($value1['isBasicUnit']) {
        //                 $arr[$key]['unitName'] = $value1['unitName'];
        //                 break;
        //             }else{
        //                 continue;
        //             }
        //         }
        //     }
        // }
        $result = empty($result) ? [] : $result;       
        $total = empty($total) ? 0 : $total;       
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        $return['total'] = $total;
        Output::instance()->object($return);
    }

    /**
     * 商家新建退货出库单
     * @param $depotId   int 仓库id
     * @param $depotName   string 仓库名称
     * @param $product   array 选中商品信息
     * @param $returnReason   string 退款原因
     * @author menghui
     */
    public function newReturnAllocation($depotId,$depotName,$product,$returnReason='')
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $customerUser = M("customer_user");
        $vendorOutstorage = M("vendor_outstorage");
        $vendorOutstorageDetail = M("vendor_outstorage_detail");
        $vendorStorageDetail = M("vendor_storage_detail");
        //$productUnit = M("module_product_unit");
        $stock = M("vendor_stock");
        Session::switchCustomer($customerId);

        /** 3. 商家数据查询 */
        $vendorOutstorage->startTrans();
        $vid = $customerUser->where("id=$cuid")->getField('vid');
        //入库数据添加
        $time = date('Y-m-d H:i:s',time());
        $outstorageNumber = $customerId . date("ymdHis") . $cuid;
        $add_outstorage['cid'] = $customerId;
        $add_outstorage['sponsorId'] = $cuid;
        $add_outstorage['sponsorName'] = $loginName;
        $add_outstorage['vid'] = $vid;
        $add_outstorage['depotId'] = $depotId;
        $add_outstorage['depotName'] = $depotName;
        $add_outstorage['sponsorTime'] = $time;
        $add_outstorage['status'] = 'delivered';
        $add_outstorage['type'] = 'return';
        $add_outstorage['deleted'] = 0;
        $add_outstorage['outstorageNumber'] = $outstorageNumber;
        $add_outstorage['returnReason'] = $returnReason;
        $newOutstorageId = $vendorOutstorage->add($add_outstorage);
        //详细出库单信息添加
        $product = json_decode($product,true);
        foreach ($product as $key => $value) {
            $add_detail['cid'] = $customerId;
            $add_detail['pid'] = $value['pid'];
            $add_detail['productName'] = $value['productName'];
            $add_detail['productUrl'] = $value['productUrl'];
            $add_detail['firstSpecificName'] = $value['firstSpecificName'];
            $add_detail['secSpecificName'] = $value['secSpecificName'];
            //考虑去掉下面这个字段,出库的时候没有单价
            //$add_detail['miunitPrice'] = $value['miunitPrice'];
            $add_detail['unit'] = $value['unit'];
            $add_detail['unitNumber'] = $value['unitNumber'];
            //获取换算关系
            //$unitConversion = $this->unitConversion($value); 
            $miunitNumber = $value['unitNumber'];
            $add_detail['miunitNumber'] = $miunitNumber;
            $add_detail['outstorageId'] = $newOutstorageId;

            //查询仓库中此商品库存量
            $where_stock = [];
            $where_stock['pid'] = $value['pid'];
            $where_stock['depotId'] = $depotId;
            $where_stock['cid'] = $customerId;
            empty($value['firstSpecificName']) ? : $where_stock['firstSpecificName'] = $value['firstSpecificName'];
            empty($value['secSpecificName']) ? : $where_stock['secSpecificName'] = $value['secSpecificName'];
            $stockInfo = $stock->field('id,totalNumber,totalValue,realNumber,productName')->where($where_stock)->find();
            //判断库存量是否足够出库
            if ($stockInfo['realNumber']  < $miunitNumber) {
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = $stockInfo['productName'].'商品库存不足以退货';
                Output::instance()->object($return);
                exit();
            }
            $result_detail = $vendorOutstorageDetail->add($add_detail); 
            if ($result_detail == false) {
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = $stockInfo['productName'].'商品出库信息存储失败';
                Output::instance()->object($return);
                exit();
            }  

            //进行判断存入此仓库的哪批货中减少的
            $where_vendorStorageDetail = [];
            $where_vendorStorageDetail['a.cid'] = $customerId;
            $where_vendorStorageDetail['a.pid'] = $value['pid'];
            empty($value['firstSpecificName']) ? : $where_vendorStorageDetail['a.firstSpecificName'] = $value['firstSpecificName'];
            empty($value['secSpecificName']) ? : $where_vendorStorageDetail['a.secSpecificName'] = $value['secSpecificName'];
            $where_vendorStorageDetail['a.surplusNumber'] = array('NEQ',0);
            $where_vendorStorageDetail['b.depotId'] = $depotId;
            $storageDetailInfo = $vendorStorageDetail->alias("a")
                ->join("LEFT JOIN wx_vendor_storage b on a.storageId=b.id")
                ->where($where_vendorStorageDetail)
                ->field('a.id,a.surplusNumber,a.productName,a.storageId,a.miunitPrice')
                ->order("id asc")
                ->select();
            if ($storageDetailInfo) {
                //获取出库商品对应的入库匹配信息
                $totalValue = $this->vendorOutstorageDetailMatch($storageDetailInfo,$miunitNumber,$newOutstorageId,$value);
                if ($totalValue === false){
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = $stockInfo['productName'] . '商品出库匹配信息存储失败';
                    Output::instance()->object($return);
                    exit();
                }

            }else {
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = $stockInfo['productName'].'商品库存不足以退货';
                Output::instance()->object($return);
                exit();
            }


            //进行库存量的减少
            $save_stock['realNumber'] = $stockInfo['realNumber'] - $miunitNumber;
            $save_stock['totalValue'] = $stockInfo['totalValue'] - $totalValue;//需要根据具体从哪一批次中调的货进行具体减少
            $save_stock['updateTime'] = $time;
            $result_stock = $stock->where("id=".$stockInfo['id'])->save($save_stock);
        }

        if ($newOutstorageId && $result_stock){
            R('Log/add', array('newDepotRefundOut', module_id_newDepotRefundOut, '退货出库', op_add, $vendorOutstorage->getLastSql(), '退货出库单添加'));
            $vendorOutstorage->commit();
            /** 5. 返回结果 */
            $return['code'] = 0;
            $return['msg'] = 'ok';
            $return['id'] = $newOutstorageId;
            Output::instance()->object($return);
            //发送站内消息
            $receiveIds = $customerUser->where(['customerId' => $customerId, 'agent' => 'business'])->getField('id', true);
            $message = '<p>仓库<b>' . $depotName . '</b>发起退货申请，请前往退货入库模块查看，<a href = "#/joymap/depot/returnDepot">前往查看</a></p>';
            PlatMessageAction::pushMessage('退货提醒', $message, $receiveIds, '', 0, 'newAllocation', '退货入库', 2, 1, 0, 0, $message, $customerId);
        }else{
            $vendorOutstorage->rollback();
            /** 5. 返回结果 */
            $return['code'] = 1;
            $return['msg'] = '信息存储错误请重试';
            Output::instance()->object($return);
        }
    }

      /**
     * 出库单列表
     * @param $start   int 开始值
     * @param $limit   int 偏移量
     * @param $search   string 搜索项
     * @param $status   string 状态值
     * @param $depotId   int 仓库id
     * @param $startTime   string 开始时间
     * @param $endTime   string  结束时间
     * @param $type   string 出库类型【allocation：调拨，return：退货】
     * @param string    $show   只显示自己商家下的数据,self
     * @author menghui
     */
    public function outAllocationList($start=0,$limit=10,$search='',$status='',$depotId='',$type='',$startTime='',$endTime='',$vid='',$show='')
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user["id"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $customerUser = M("customer_user");
        $vendorOutstorage = M("vendor_outstorage");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        //判断角色，如果是商家的话需要加上商家的id限制
        if ($depotId){
            $where['a.depotId'] = $depotId;
        }else{
            if ($vid) {
                $userVid = $vid;
                $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                $where['a.vid'] = array('IN', $vids);
            }else {
                if (Session::isVendor()){
                    //mh修改于20180622
                    //$userVid = $customerUser->where("id=$cuid")->getField('vid');
                    //$where['a.vid'] = array('eq', $userVid);
                    $userVid = $customerUser->where("id=$cuid")->getField('vid');
                    //mh修改于20180620，用户渠道体系升级，改用in查询
                    if ($show) {
                        $where['a.vid'] = array('eq', $userVid);
                    }else {
                        $vids = R("Vendor/getMivendorChildList",array($userVid,'string'));
                        $where['a.vid'] = array('IN', $vids);
                    }
                }
            }
        }

        if (!empty($search)) {     // 关键字查询
            $arg['a.outstorageNumber'] = array('like', "%$search%");
            //如果是商家看确认订单的时候搜索项中的操作人筛选是最后的确认收货人
            if ($status == 'confirm' && Session::isVendor()){
                $arg['a.confirmName'] = array('like', "%$search%");
            }else{
                $arg['a.sponsorName'] = array('like', "%$search%");
            }           
            $arg['_logic'] = "OR";
            $where["_complex"] = $arg;
        }
        //状态筛选、商家筛选、仓库筛选、类型筛选
        if ($status) {
            $status = explode(',',$status);
            $where['a.status'] = array("IN",$status); 
        }
        $type? $where['a.type'] = $type : '';
        //时间筛选
        if ($startTime != '' && $endTime != '') {
            $where['a.sponsorTime'] = array(array('egt', $startTime), array('elt', date('Y-m-d', strtotime("$endTime +1 day"))));
        } else if ($startTime != '') {
            $where["a.sponsorTime"] = array('egt', $startTime);
        } else if ($endTime != '') {
            $where["a.sponsorTime"] = array('elt', date('Y-m-d', strtotime("$endTime +1 day")));
        }
        $where['a.cid'] = $customerId;
        $where['a.deleted'] = 0;
        $total = $vendorOutstorage->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->where($where)
                ->count();  
        $result = $vendorOutstorage->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->field("a.*,b.name")
                ->where($where)
                ->order("a.id desc")
                ->limit($start,$limit)
                ->select();
        $result = empty($result) ? [] : $result;       
        $total = empty($total) ? 0 : $total;       
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        $return['total'] = $total;
        Output::instance()->object($return);
    }
      /**
     * 出库单基本信息查询
     * @param $id   int 入库单id
     * @author menghui
     */
    public function outAllocationBasicInfo($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorOutstorage = M("vendor_outstorage");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $where['a.id'] = $id;
        $result = $vendorOutstorage->alias('a')
                ->join("left join wx_mivendor b on a.vid=b.id")
                ->field("a.*,b.name")
                ->where($where)
                ->find();  
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        Output::instance()->object($return);
    }

    /**
     * 出库单商品信息查询
     * @param $id   int 入库单id
     * @param $start   int 开始量
     * @param $limit   int 偏移量
     * @author menghui
     */
    public function outAllocationProductInfo($id,$start=0,$limit=10)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $detail = M("vendor_outstorage_detail");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $total = $detail->where("outstorageId=$id")->count();
        $total = empty($total) ? 0 : $total; 
        $result = $detail->where("outstorageId=$id")->limit($start,$limit)->select();
        $result = empty($result) ? [] : $result; 
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '数据返回';
        $return['data'] = $result;
        $return['total'] = $total;
        Output::instance()->object($return);
    }

    /**
     * 系统管理员拒收退货
     * @param $id   int 出库单id
     * @param $refundReason   string 拒收原因
     * @author menghui
     */
    public function refuseRefundAllocation($id,$refuseReason)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorOutstorage = M("vendor_outstorage");
        $match = M("vendor_outstorage_detail_match");
        $detail = M("vendor_storage_detail");
        $stock = M("vendor_stock");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $vendorOutstorageInfo = $vendorOutstorage->field('outstorageNumber,status,depotId,sponsorId,sponsorName')->where("id=$id")->find();
        if ($vendorOutstorageInfo['status'] == 'delivered') {
            $vendorOutstorage->startTrans();
            $time = date('Y-m-d H:i:s',time());
            $save_data['status'] = 'refuse';
            $save_data['operatorTime'] = $time;
            $save_data['operatorId'] = $cuid;
            $save_data['operatorName'] = $loginName;
            $save_data['operatorReason'] = $refuseReason;
            $status_result = $vendorOutstorage->where("id=$id")->save($save_data);
            /** 4. 进行数据存储存储回去到入库表中 ,以及库存表信息增加*/
            //首先进行数据查询
            $matchInfo = $match->where("outstorageId=$id")->select();
            foreach ($matchInfo as $key=>$value) {
                //进行原来入库单剩余数目增加
                $where_ouestorage_storageId = [];
                $where_ouestorage_storageId['cid'] = $customerId;
                $where_ouestorage_storageId['storageId'] = $value['storageId'];
                $where_ouestorage_storageId['pid'] = $value['pid'];
                empty($value['firstSpecificName']) ? : $where_ouestorage_storageId['firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_ouestorage_storageId['secSpecificName'] = $value['secSpecificName'];
                $storageDetail = $detail->where($where_ouestorage_storageId)->setInc('surplusNumber',$value['miunitNumber']);
                if ($storageDetail == false) {
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = '拒收失败，请重试';
                    Output::instance()->object($return);
                    exit();
                }
                //进行库存量以及库存价格的增加
                $where_stock = [];
                $where_stock['cid'] = $customerId;
                $where_stock['pid'] = $value['pid'];
                $where_stock['depotId'] = $vendorOutstorageInfo['depotId'];
                empty($value['firstSpecificName']) ? : $where_stock['firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_stock['secSpecificName'] = $value['secSpecificName'];
                $stockInfo = $stock->field('realNumber,totalValue')->where($where_stock)->find();

                $save_stock_info['realNumber'] = $stockInfo['realNumber'] + $value['miunitNumber'];
                $save_stock_info['totalValue'] = $stockInfo['totalValue'] + $value['totalValue'];
                $save_stock_info['updateTime'] = $time;
                $save_stock = $stock->where($where_stock)->save($save_stock_info);
                if ($save_stock == false) {
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = '拒收失败，请重试';
                    Output::instance()->object($return);
                    exit();
                }

            }

            /** 5. 返回结果 */
            if ($status_result !== false) {
                R('Log/add', array('newDepotRefundOut', module_id_newDepotRefundOut, '退货出库', op_update, $vendorOutstorage->getLastSql(), '拒收'.$vendorOutstorageInfo['sponsorName'].'的退货单，原因为：'.$refuseReason));
                $vendorOutstorage->commit();
                $return['code'] = 0;
                $return['msg'] = 'ok';
                Output::instance()->object($return);
                //发送站内消息
                $receiveIds[] = $vendorOutstorageInfo['sponsorId'];
                $message = '<p>您的出库单号为' . $vendorOutstorageInfo['outstorageNumber'] . '的退货出库申请被拒收，请前往退货出库模块查看，<a href = "#/joymap/depot/returnDepot">前往查看</a></p>';
                PlatMessageAction::pushMessage('退货拒收提醒', $message, $receiveIds, '', 0, 'newAllocation', '退货出库', 2, 1, 0, 0, $message, $customerId);
            }else{
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = '拒收失败，请重试';
                Output::instance()->object($return);
            }
        }else{
            $return['code'] = 1;
            $return['msg'] = '此状态的退货单不能拒收';
            Output::instance()->object($return);
        }     
    }

    /**
     * 系统管理员确认出库单
     * @param $id   int 入库单id
     * @param $product   array 商品信息
     * @author menghui
     */
    public function confirmOutallocation($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorOutstorage = M("vendor_outstorage");
        $vendorOutstorageDetail = M("vendor_outstorage_detail");
        $stock = M("vendor_stock");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $vendorOutstorage->startTrans();
        $outstorage_info = $vendorOutstorage->field('outstorageNumber,status,vid,depotId,sponsorId,depotName,sponsorName')->where("id=$id")->find();
        if ($outstorage_info['status'] == 'delivered') {
            //修改出库单状态
            $time = date('Y-m-d H:i:s',time());
            $save_data['status'] = 'confirm';
            $save_data['operatorTime'] = $time;
            $save_data['operatorId'] = $cuid;
            $save_data['operatorName'] = $loginName;
            $status_result = $vendorOutstorage->where("id=$id")->save($save_data);

            //出库单详细商品信息查询
            $detailInfo = $vendorOutstorageDetail->where("outstorageId=$id")->select();
            foreach ($detailInfo as $key=>$value) {
                //进行此商品库存量查询
                $where_stock = [];
                $where_stock['cid'] = $customerId;
                $where_stock['pid'] = $value['pid'];
                $where_stock['depotId'] = $outstorage_info['depotId'];
                empty($value['firstSpecificName']) ? : $where_stock['firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_stock['secSpecificName'] = $value['secSpecificName'];
                $stockInfo = $stock->field('totalNumber,totalValue')->where($where_stock)->find();
                //库存总量减少，以及时间的修改
                $save_stock_info['totalNumber'] = $stockInfo['totalNumber'] - $value['miunitNumber'];
                $save_stock_info['updateTime'] = $time;
                $save_stock = $stock->where($where_stock)->save($save_stock_info);

                if ($save_stock == false) {
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = '确认失败，请重试';
                    Output::instance()->object($return);
                    exit();
                }

            }               
            /** 5. 返回结果 */
            if ($status_result !== false){
                 R('Log/add', array('newDepotRefundOut', module_id_newDepotRefundOut, '退货出库', op_update, $vendorOutstorage->getLastSql(), '确认'.$outstorage_info['sponsorName'].'的退货单'));
                $vendorOutstorage->commit();
                /** 5. 返回结果 */
                $return['code'] = 0;
                $return['msg'] = 'ok';
                Output::instance()->object($return);
                //发送站内消息
                $receiveIds[] = $outstorage_info['sponsorId'];
                $message = '<p>您的出库单号为' . $outstorage_info['outstorageNumber'] . '的退货出库申请已被确认，请前往退货出库模块查看，<a href = "#/joymap/depot/returnDepot">前往查看</a></p>';
                PlatMessageAction::pushMessage('退货确认提醒', $message, $receiveIds, '', 0, 'newAllocation', '退货出库', 2, 1, 0, 0, $message, $customerId);
            }else{
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = '出库确认失败请重试';
                Output::instance()->object($return);
            }
            
        }else{
            $vendorOutstorage->rollback();
            $return['code'] = 1;
            $return['msg'] = '此状态的出库单不能确认';
            Output::instance()->object($return);
        }     
    }

    /**
     * 供应商确认商品发货
     * @param $id   int 入库单id
     * @author menghui
     */
    public function confirmOutallocationDelivery($id)
    {
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        $loginName = Session::$user['fullName'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorOutstorage = M("vendor_outstorage");
        $vendorOutstorageDetail = M("vendor_outstorage_detail");
        $vendorStorageDetail = M("vendor_storage_detail");
        $vendorOutstorageMatch = M("vendor_outstorage_detail_match");
        $stock = M("vendor_stock");
        Session::switchCustomer($customerId);

        /** 3. 调拨单数据查询 */
        $vendorOutstorage->startTrans();
        $outstorage_info = $vendorOutstorage->field('id,status,vid,depotId,depotName,sponsorName')->where("id=$id")->find();
        if ($outstorage_info['status'] == 'requested') {
            //修改出库单状态
            $time = date('Y-m-d H:i:s',time());
            $save_data['status'] = 'delivered';
            $save_data['operatorTime'] = $time;
            $save_data['operatorId'] = $cuid;
            $save_data['operatorName'] = $loginName;
            $status_result = $vendorOutstorage->where("id=$id")->save($save_data);

            //出库单详细商品信息查询
            $detailInfo = $vendorOutstorageDetail->where("outstorageId=$id")->select();
            foreach ($detailInfo as $key=>$value) {
                //进行此商品库存量查询
                $where_stock = [];
                $where_stock['cid'] = $customerId;
                $where_stock['pid'] = $value['pid'];
                $where_stock['depotId'] = $outstorage_info['depotId'];
                empty($value['firstSpecificName']) ? : $where_stock['firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_stock['secSpecificName'] = $value['secSpecificName'];
                $stockInfo = $stock->field('id,totalValue,totalNumber,productName,realNumber')->where($where_stock)->find();
                //判断库存量是否足够出库
                if ($stockInfo['realNumber']  < $value['miunitNumber']) {
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = $stockInfo['productName'].'商品库存不足以出货';
                    Output::instance()->object($return);
                    exit();
                }

                 //进行判断从哪批货中减少的
                $where_vendorStorageDetail = [];
                $where_vendorStorageDetail['a.cid'] = $customerId;
                $where_vendorStorageDetail['a.pid'] = $value['pid'];
                empty($value['firstSpecificName']) ? : $where_vendorStorageDetail['a.firstSpecificName'] = $value['firstSpecificName'];
                empty($value['secSpecificName']) ? : $where_vendorStorageDetail['a.secSpecificName'] = $value['secSpecificName'];
                $where_vendorStorageDetail['a.surplusNumber'] = array('NEQ',0);
                $where_vendorStorageDetail['b.depotId'] = $outstorage_info['depotId'];
                $storageDetailInfo = $vendorStorageDetail->alias("a")
                    ->join("LEFT JOIN wx_vendor_storage b on a.storageId=b.id")
                    ->where($where_vendorStorageDetail)
                    ->field('a.id,a.surplusNumber,a.productName,a.storageId,a.miunitPrice')
                    ->order("id asc")
                    ->select();
                if ($storageDetailInfo) {
                    $totalValue = $this->vendorOutstorageDetailMatch($storageDetailInfo,$value['miunitNumber'],$outstorage_info['id'],$value);
                    if ($totalValue === false){
                        $vendorOutstorage->rollback();
                        $return['code'] = 1;
                        $return['msg'] = $stockInfo['productName'] . '商品出库匹配信息存储失败';
                        Output::instance()->object($return);
                        exit();
                    }

                }else {
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = $stockInfo['productName'].'商品库存不足以退货';
                    Output::instance()->object($return);
                    exit();
                }


                //进行库存量的减少
                $save_stock['realNumber'] = $stockInfo['realNumber'] - $value['miunitNumber'];
                $save_stock['totalValue'] = $stockInfo['totalValue'] - $totalValue;
                $save_stock['updateTime'] = $time;
                $result_stock = $stock->where("id=".$stockInfo['id'])->save($save_stock);

            }               
            /** 5. 返回结果 */
            if ($status_result !== false){
                 R('Log/add', array('newDepotRefundOut', module_id_newDepotRefundOut, '订单出库', op_update, $vendorOutstorage->getLastSql(), '确认用户'.$outstorage_info['sponsorName'].'的订单出库'));
                $vendorOutstorage->commit();
                /** 5. 返回结果 */
                $return['code'] = 0;
                $return['msg'] = 'ok';
                Output::instance()->object($return);
            }else{
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = '出库确认失败请重试';
                Output::instance()->object($return);
            }
            
        }else{
            $vendorOutstorage->rollback();
            $return['code'] = 1;
            $return['msg'] = '此状态的出库单不能确认发货';
            Output::instance()->object($return);
        }     
    }


    /** 出库商品匹配入库信息
     * @param $storageInfo  入库信息
     * @param $miunitNumber  总数量
     * @param $outstorageId  出库id
     * @param $productInfo   商品信息
     * @return bool|int
     */
    public function vendorOutstorageDetailMatch($storageInfo,$miunitNumber,$outstorageId,$productInfo){
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $vendorOutstorage = M("vendor_outstorage");
        $vendorStorageDetail = M("vendor_storage_detail");
        $vendorOutstorageMatch = M("vendor_outstorage_detail_match");
        Session::switchCustomer($customerId);
        $stocknum = $miunitNumber;
        $totalValue = 0;
        foreach ($storageInfo as $key => $value) {
            //判断剩余需要减少的数量是否大于此条入库剩余量，则进行此条入库信息的剩余量置0，以及进行匹配信息的增加
            if ($stocknum > $value['surplusNumber']) {
                $stocknum -= $value['surplusNumber'];
                $add_match['cid'] = $customerId;
                $add_match['pid'] = $productInfo['pid'];
                $add_match['firstSpecificName'] = $productInfo['firstSpecificName'];
                $add_match['secSpecificName'] = $productInfo['secSpecificName'];
                $add_match['miunitNumber'] = $value['surplusNumber'];
                $add_match['miunitPrice'] = $value['miunitPrice'];
                $add_match['totalValue'] = $value['surplusNumber'] * $value['miunitPrice'];
                $add_match['storageId'] = $value['storageId'];
                $add_match['outstorageId'] = $outstorageId;
                $newMatchId = $vendorOutstorageMatch->add($add_match);
                $totalValue += $value['surplusNumber'] * $value['miunitPrice'];
                $result_storage_detail = $vendorStorageDetail->where('id=' . $value['id'])->setField('surplusNumber', 0);
                log::write('出库商品匹配入库信息outstorageId为'.$outstorageId.' sql: '.$vendorOutstorageMatch->getLastSql());
                log::write('出库商品修改入库信息outstorageId为'.$outstorageId.' sql: '.$vendorStorageDetail->getLastSql());
                if (($newMatchId == false) || ($result_storage_detail == false)) {
                    $vendorOutstorage->rollback();
                    $return['code'] = 1;
                    $return['msg'] = $value['productName'] . '商品出库匹配信息存储失败';
                    Output::instance()->object($return);
                    exit();
                }
            } else {
                //判断剩余需要减少的数量是否小于等于此条入库剩余量，则进行此条入库信息的剩余量减少并退出循环，以及进行匹配信息的增加
                $add_match['cid'] = $customerId;
                $add_match['pid'] = $productInfo['pid'];
                $add_match['firstSpecificName'] = $productInfo['firstSpecificName'];
                $add_match['secSpecificName'] = $productInfo['secSpecificName'];
                $add_match['miunitNumber'] = $stocknum;
                $add_match['miunitPrice'] = $value['miunitPrice'];
                $add_match['totalValue'] = $stocknum * $value['miunitPrice'];
                $add_match['storageId'] = $value['storageId'];
                $add_match['outstorageId'] = $outstorageId;
                $newMatchId = $vendorOutstorageMatch->add($add_match);
                $totalValue  += $stocknum * $value['miunitPrice'];

                $result_storage_detail = $vendorStorageDetail->where('id=' . $value['id'])->setField('surplusNumber', $value['surplusNumber'] - $stocknum);
                log::write('出库商品匹配入库信息outstorageId为'.$outstorageId.' sql: '.$vendorOutstorageMatch->getLastSql());
                log::write('出库商品修改入库信息outstorageId为'.$outstorageId.' sql: '.$vendorStorageDetail->getLastSql());
                if (($newMatchId == false) || ($result_storage_detail == false)) {
                    return false;
                }
                return $totalValue;
            }
        }

    }


    /**
     * 更改出库单的仓库
     * @param $depotId          仓库id
     * @param $outstorageId     出库单id
     */
    public function saveMiuOut($depotId,$outstorageId){
        /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $depot = M("depot");
        $vendorOutstorage = M("vendor_outstorage");
        Session::switchCustomer($customerId);

        /** 3. 查询仓库名称 */
        $depotData = $depot->where(['id' => $depotId])->field('id as depotId,name as depotName,vid')->find();

        /** 4. 修改 */
        $result = $vendorOutstorage->where(['id' => $outstorageId])->save($depotData);

        /** 5. 返回 */
        if(is_numeric($result)){
            $return['code'] = 0;
            $return['msg'] = 'ok';
            Output::instance()->object($return);
        }else{
            $return['code'] = 1;
            $return['msg'] = '修改失败';
            Output::instance()->object($return);
        }
    }

    private function unitConversion($value)
    {
         /** 1. 判断用户身份信息 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $cuid = Session::$user['id'];
        Session::switchCustomer(0);

        /** 2. 创建仓库表数据模型 */
        $productUnit = M("module_product_unit");
        Session::switchCustomer($customerId);

        if ($value['unit']) {
            $where_unit['pid'] = $value['pid'];
            $where_unit['unitName'] = $value['unit'] ;
            $unitConversion = $productUnit->where($where_unit)->getField('unitConversion');
        }else {
            $unitConversion = 1;
        }

        return $unitConversion;
            
    }
}